package micotime.com.amap_plugin.map.channel;


import android.content.Context;
import android.graphics.BitmapFactory;
import android.graphics.Point;
import android.view.animation.Interpolator;

import com.amap.api.location.AMapLocationClient;
import com.amap.api.maps.AMap;
import com.amap.api.maps.TextureMapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.NavigateArrowOptions;
import com.amap.api.maps.model.animation.Animation;
import com.amap.api.maps.model.animation.TranslateAnimation;
import com.amap.api.services.core.LatLonPoint;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import micotime.com.amap_plugin.map.common.MarkerOptionsUtils;
import micotime.com.amap_plugin.map.model.UnifiedMarkerOptions;

public class MarkerMethodChannel extends AbstractMethodChannel {

    /**
     * 添加标记
     */
    private final static String METHOD_CHANNEL_ADD_MARKER = "addMarker";
    /**
     * 添加多个标记
     */
    private final static String METHOD_CHANNEL_ADD_MARKERS = "addMarkers";
    /**
     * 添加大头针
     */
    private final static String METHOD_CHANNEL_ADD_MARKER_PIN = "addMarkerPin";

    private Marker locationMarker;

    public MarkerMethodChannel(Context context, TextureMapView mapView) {
        super(context,mapView);
        this.aMap.setOnCameraChangeListener(new AMap.OnCameraChangeListener() {
            @Override
            public void onCameraChange(CameraPosition cameraPosition) {

            }

            @Override
            public void onCameraChangeFinish(CameraPosition cameraPosition) {
                startJumpAnimation();
            }
        });
    }

    /**
     * 屏幕中心marker 跳动
     */
    public void startJumpAnimation() {

        if (locationMarker != null ) {
            //根据屏幕距离计算需要移动的目标点
            final LatLng latLng = locationMarker.getPosition();
            Point point =  aMap.getProjection().toScreenLocation(latLng);
            point.y -= dip2px(this.context,50);
            LatLng target = aMap.getProjection()
                    .fromScreenLocation(point);
            //使用TranslateAnimation,填写一个需要移动的目标点
            Animation animation = new TranslateAnimation(target);
            animation.setInterpolator(new Interpolator() {
                @Override
                public float getInterpolation(float input) {
                    // 模拟重加速度的interpolator
                    if(input <= 0.5) {
                        return (float) (0.5f - 2 * (0.5 - input) * (0.5 - input));
                    } else {
                        return (float) (0.5f - Math.sqrt((input - 0.5f)*(1.5f - input)));
                    }
                }
            });
            //整个移动所需要的时间
            animation.setDuration(600);
            //设置动画
            locationMarker.setAnimation(animation);
            //开始动画
            locationMarker.startAnimation();

        } else {
            //Log.e("ama","screenMarker is null");
        }
    }


    @Override
    public void process(MethodCall methodCall, MethodChannel.Result result) {
       switch (methodCall.method){
           case METHOD_CHANNEL_ADD_MARKER:
              result.success( addMarker(methodCall));
               break;
           case METHOD_CHANNEL_ADD_MARKERS:
               result.success(addMarkers(methodCall));
               break;
           case METHOD_CHANNEL_ADD_MARKER_PIN:
               result.success(addMarkerPin(methodCall));
               break;
       }
    }

    /**
     * 添加地图标记
     * @param call
     * @return  返回MarkerId
     */
    private String addMarker(MethodCall call){
        UnifiedMarkerOptions markerOptions = MarkerOptionsUtils.getMarkerOptions(call);
        Marker marker = this.aMap.addMarker(markerOptions.getMarkerOptions());
        if(markerOptions.getAnimation() != null){
            Animation animation = markerOptions.getAnimation();
            marker.setAnimation(animation);
            marker.startAnimation();
        }
        return marker.getId();
    }

    /**
     * 添加多个markers
     * @param call
     * @return
     */
    @SuppressWarnings("unchecked")
    private List<String> addMarkers(MethodCall call){
        List<String> rev = new ArrayList<>();
        boolean moveToCenter = false;
        if(call.argument("moveToCenter") != null){
            moveToCenter = (boolean)call.argument("moveToCenter");
        }
        if(!(call.argument("list") instanceof ArrayList))return rev;
        List<UnifiedMarkerOptions> markerOptionsList =
                MarkerOptionsUtils.getMarkerOptionsList((ArrayList<Map>)call.argument("list"));
        ArrayList<MarkerOptions> list = new ArrayList<>();
        if(markerOptionsList == null)return rev;
        for (UnifiedMarkerOptions markerOptions : markerOptionsList) {
            list.add(markerOptions.getMarkerOptions());
        }
        ArrayList<Marker> markerArrayList =  this.aMap.addMarkers(list,moveToCenter);
        for (Marker marker : markerArrayList) {
            rev.add(marker.getId());
        }
        return rev;
    }

    /**
     * 添加大头针
     * @param call
     * @return
     */
    private String addMarkerPin(MethodCall call){
        //UnifiedMarkerOptions markerOptions = MarkerOptionsUtils.getMarkerOptions(call);
        byte[] data = (byte[])call.arguments;
        MarkerOptions markerOptions =
                new MarkerOptions().icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeByteArray(data,0,data.length)));
        locationMarker = addMarkerInScreenCenter(markerOptions);
        locationMarker.setAnimation(new TranslateAnimation(locationMarker.getPosition()));
        final LatLng latLng = locationMarker.getPosition();
        Point point =  aMap.getProjection().toScreenLocation(latLng);
        point.y -= dip2px(this.context,100);
        LatLng target = aMap.getProjection()
                .fromScreenLocation(point);

     return locationMarker.getId();
    }

    //dip和px转换
    private static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.6f);
    }

    //添加指针
    private Marker addMarkerInScreenCenter(MarkerOptions markerOptions) {
        LatLng latLng = aMap.getCameraPosition().target;
        Point screenPosition = aMap.getProjection().toScreenLocation(latLng);
        Marker  locationMarker = aMap.addMarker(markerOptions
                .anchor(0.5f,0.5f));
        //设置Marker在屏幕上,不跟随地图移动
        locationMarker.setPositionByPixels(screenPosition.x,screenPosition.y);
        locationMarker.setZIndex(1);
        return locationMarker;
    }
}
